/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package swym.client;

import java.io.*;
import java.net.*;
import swym.server.file.*;
import swym.server.*;
import swym.protocol.*;
/**
 *
 * @author henryja
 */
public class FileChunkSender extends Thread
{
    private File tempDir;
    private User user;
    private Client client;
    private String serverIP;
    private int port;
        
    public FileChunkSender(String serverIP, int port, User user, Client client)
    {
        tempDir = new File("temp");
        this.serverIP = serverIP;
        this.port = port;
        this.user = user;
        this.client = client;
    }
    
    public void run()
    {
        while(true)
        {
            if(tempDir.exists() && tempDir.isDirectory())
                scanDir(tempDir);
            
            try{Thread.sleep(1000);}catch(Exception ie){ie.printStackTrace();}
        }       
    }
    
    private boolean scanDir(File dir)
    {
        System.out.println("Scanning : " + dir.getAbsolutePath());
        
        boolean representsFile = true;
        
        File[] files = dir.listFiles();
        if(files.length > 0)
        {
            for(File f : dir.listFiles())
                if(f.isDirectory())
                {
                    representsFile = false;
                    
                    if(!f.getAbsolutePath().endsWith("~"))
                        if(scanDir(f))
                        {
                            System.out.println(f.getAbsolutePath());
                            if(sendFile(f))
                                f.delete();         //this will only work if the filechunks are delted as they are sent but what to do if there is 
                        }                              //an error sending a filechunk should it still be deleted should it keep all filechunks for a reattempt
                }
        }
        else
        {
            dir.delete();
            representsFile = false;
        }
        
        return representsFile;        
    }
    
    private boolean sendFile(File fileFolder)
    {
        boolean finished = false;
        String filePath = fileFolder.getAbsolutePath().replace(tempDir.getAbsolutePath(), "");
        String version = client.getName() + "-" + filePath.substring(filePath.lastIndexOf(".")+1);
        filePath = filePath.substring(0,filePath.lastIndexOf(".")).replace("temp","");

        SyncedFile sync = new SyncedFile(user, filePath, version);
        sync.setSize( fileFolder.listFiles().length );
        FileActionMessage message = new FileActionMessage( user.getName(), client.getName(),  FileAction.eFileActionType.NEW, 1 ); 
        message.setFileInformation( sync );
        try
        {
            Socket socket = new Socket(serverIP,port);
            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); 
            ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

            out.writeObject( new LoginActionMessage( user.getName(), client.getName(), 0 ) );
            out.flush();

            ConfirmActionMessage confirmMsg = (ConfirmActionMessage)in.readObject();
            if ( confirmMsg.getReturnCode() == 0 )
            {
                out.writeObject( message );
                out.flush();
                //open connection to server
                //get files in this directory and send the filechunks
                ObjectInputStream chunkIn;
                for ( File chunk : fileFolder.listFiles() )
                {
                        // notice the different file action type – CHUNK; it indicates that
                        // this message is really a container for a file chunk.
                        message = new FileActionMessage( user.getName(), client.getName(),  FileAction.eFileActionType.CHUNK, 1 );
                        message.setFileInformation(sync);

                        chunkIn = new ObjectInputStream(new FileInputStream(chunk));
                        message.setPayload( chunkIn.readObject());
                        chunkIn.close();
                        
                        out.writeObject( message );
                        out.flush();
                }
                //does this confirmation get sent after every filechuinksend if not how does the server know it is the last chunk
                //the synced file does not have this info
                confirmMsg = (ConfirmActionMessage)in.readObject(); //what should happen if this is not received
            }

            CloseActionMessage closeActionMessage = new CloseActionMessage( user.getName(), client.getName(), 2 );
            out.writeObject ( closeActionMessage );
            out.flush();
            out.close();
            in.close();
            socket.close();
            
            for ( File f : fileFolder.listFiles() )
                f.delete();
                      
            finished = true;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        
        return finished;
    }
}
